<?php

/**
 * Table/ContratTable.php
 */

namespace RHX\Model\Table;

use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\Contrat;

class ContratTable extends AbstractTableGateway {

    /**
     *
     * @var string
     */
    protected $table = 'rh_contrat';

    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new Contrat($adapter));
	$this->initialize();
    }

    /**
     * Tous les contrats
     *
     * @return ResultSet
     */
    public function getAll() {
	return $this->select();
    }

    /**
     * Récupérer un Contrat
     *
     * @param int $id
     * @return Contrat
     * @throws \Exception
     */
    public function get($id) {
	$row = $this->select(array('id' => $id))
		->current();
	if (!$row) {
	    throw new \Exception("Impossible de trouver le Contrat #$id");
	}

	return $row;
    }

    /**
     * Vérifie la présence d'un Contrat
     *
     * @param int $id
     * @return boolean
     */
    public function verify($id) {
	try {
	    $this->get($id);
	    return true;
	}
	catch (\Exception $ex) {
	    return false;
	}
    }

    /**
     * Efface un Contrat
     *
     * @param int $id
     * @return int
     */
    public function erase($id) {
	return $this->delete(array('id' => $id));
    }

    /**
     * Sauvegarder un contrat
     *
     * @param \RHX\Model\Object\Contrat $contrat
     * @return int
     */
    public function save(Contrat $contrat) {
	$data	 = array(
	    'type_id'	 => $contrat->type_id,
	    'libelle'	 => $contrat->libelle,
	    'debut'		 => $contrat->debut,
	    'fin'		 => $contrat->fin,
	    'motif_depart'	 => $contrat->motif_depart,
	);
	$id	 = (int) $contrat->id;
	if ($id == 0) {
	    $this->insert($data);
	    $id = $this->getLastInsertValue();
	}
	elseif ($this->verify($id)) {
	    $this->update($data, array('id' => $id));
	}

	return $id;
    }

}

?>
